(function (T) {
  var serverUrl = window.location.origin;

  let sdk_name = "anyPortal";
  console.log('----------serverUrl--------')
  console.log(serverUrl)
  console.log('===========serverUrl=======')
  let _anyPortal = new (function () {
    var _config;
    this.ready = function (param, func) {
      let url = window.location.href;
      if (url.indexOf("#") > -1) {
        url = url.split("#")[0];
      }

      let ajaxUrl = `${serverUrl}/zm/zmglpt-integration-web/mobile/signJsapi.do?signUrl=${url}&t=${new Date().getTime()}`

      console.log('ajaxUrl---', ajaxUrl)

      /**
       * 钉钉初始化
       */
      post_methods(
          ajaxUrl,
          {},
          function (data) {
            setTimeout(function () {
              _config = data.bean;
              console.log('---_config----', JSON.stringify(_config))
              anyPortal.config({
                agentId: param.agentId,
                corpId: _config.corpId,
                timeStamp: _config.timestamp,
                nonceStr: _config.nonceStr,
                signature: _config.signature,
                jsApiList: param.jsApiList
              });
              dd.error(function (err) {
                console.log('---d--dderr-')
                console.log("dd error: " + JSON.stringify(err));
                console.log('dd--err--')
              });
              dd.ready(function () {
                console.log('-ready start--')
                func();
              });
            }, 1000);
          },
          function (err) {
            setTimeout(() => {
              console.log('----', err)
              let code = err.responseJSON.code;
              if (Number(code) === 500) {
                console.log('--------success- err------')
                location.reload()
                // anyPortal.ready(param, func)
                console.log('--------success--- err----')
              }
            }, 500)
            console.log('err', err)
          }
      )
    };

    //config
    this.config = function (data) {
      dd.config(data);
    };

    //error
    this.error = function (data) {
      console.log('adsadadahda')
      dd.error(data);
      console.log('adsadadassss----hda')
    };

    /**
     * 验证钉钉，获取用户鉴权code
     * @param func
     */
    this.requestAuthCode = function (func) {
      console.log("corpId:", _config.corpId)
      dd.runtime.permission.requestAuthCode({
        corpId: _config.corpId,
        onSuccess: function (info) {
          func.onSuccess(info)
        },
        onFail: function (err) {
          func.onFail(err);
        }
      });
      // dd.getAuthCode({
      //   corpId: _config.corpId,
      //   onSuccess: function (info) {
      //     console.log('----', info)
      //     func.onSuccess(info)
      //   },
      //   onFail: function (err) {
      //     console.log('-11-11-1', err)
      //     func.onFail(err);
      //   }
      // });
    }

    /**
     * 获取用户信息
     * @param param 钉钉提供的code
     * @param func 方法对象
     */
    this.getAccountInfo = function (param, func) {
      let ajaxUrl = `${serverUrl}/zm/zmglpt-integration-web/mobile/getAccountInfo.do?code=${param}&t=${new Date().getTime()}`
      console.log('ajaxUrl------getAccountInfo', ajaxUrl)
      post_methods(
          ajaxUrl,
          {},
          function (data) {
            func.onSuccess(data)
          },
          function (err) {
            func.onFail(err)
          }
      )
    }

    this.saveAppAccountRel = function (param, func) {
      let ajaxUrl = `${serverUrl}/zm/zmglpt-integration-web/mobile/saveAppAccountRel.do?t=${new Date().getTime()}`
      let params = {
        "thirdPartyUuid": param.thirdPartyUuid,
        "accountUuid": param.accountUuid
      }
      console.log('ajaxUrl------saveAppAccountRel', ajaxUrl)
      console.log('ajaxUrl------params', param)
      console.log('ajaxUrl------saveAppAccountRel----------')
      post_methods(
          ajaxUrl,
          JSON.stringify(params),
          function (data) {
            func.onSuccess(data)
          },
          function (err) {
            func.onFail(err)
          }
      )
    }
  })

  function _setNameSpace(obj, rootName) {
    if (rootName && rootName !== "") {
      obj["_namespace"] = rootName;
    }
    for (const key in obj) {
      let type = typeof obj[key];
      if (type === "object") {
        //console.log("object:", key);
        obj[key]["_namespace"] = (obj["_namespace"] ? obj["_namespace"] : "") + "." + key;
        _setNameSpace(obj[key]);
      } else if (type === "function") {
        obj[key]["_fullName"] = obj["_namespace"] + "." + key;
        //console.log("function:", key);
        //console.log("_fullName:", obj["_namespace"] + "." + key);
      }
    }
  }
  _setNameSpace(_anyPortal, sdk_name);


  const _handler = {
    get(target, key) {
      console.log(target, key)
      if (typeof target[key] === "object") {
        return new Proxy(target[key], _handler);
      } else if (typeof target[key] === "function") {
        return new Proxy(target[key], {
          apply(t, ctx, args) {
            let fnFullName = target[key]["_fullName"];
            let result = Reflect.apply(...arguments);
            console.log("result::", result)
            return result;
          }
        });
      }
    }
  };

  // ajax-post方法
  const post_methods = function (url, data, successFun, errorFun) {
    $.ajax({
      type: "post",
      url: url,
      data: data,
      cache: false,
      dataType: "JSON",
      contentType: "application/json; charset=UTF-8",
      success: function (data) {
        successFun(data)
      },
      error: function (err) {
        errorFun(err)
      }
    })
  }

  T[sdk_name] = new Proxy(_anyPortal, _handler);
})(window);
